package com.yida.common.core.utils.bean;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.yida.common.core.utils.StringUtils;
import com.yida.common.core.utils.reflect.ReflectUtils;



/**
 * 树结构构建
 * @author hmh
 *
 */
public class BeanTreeUtils<T> {
	
	@SuppressWarnings("unchecked")
	public List<T> getChildPerms(List<T> list, Long parentId){
		List<T> returnList = new ArrayList<>();
		for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
			T object = (T) iterator.next();
			// 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
			Long objectParentId = ReflectUtils.getFieldValue(object, "parentId");	
			if (objectParentId == parentId) {
				recursionFn(list, object);
				returnList.add(object);
			}
		}
		return returnList;
	}
	
	/**
	 * 递归列表
	 * 
	 * @param list
	 * @param t
	 */
	private void recursionFn(List<T> list, T t) {
		// 得到子节点列表
		List<T> childList = getChildList(list, t);
		ReflectUtils.setFieldValue(t, "children", childList);
		for (T tChild : childList) {
			if (hasChild(list, tChild)) {
				recursionFn(list, tChild);
			}
		}
	}

	/**
	 * 得到子节点列表
	 */
	@SuppressWarnings("unchecked")
	private List<T> getChildList(List<?> list, T t) {
		List<T> tlist = new ArrayList<T>();
		Iterator<T> it = (Iterator<T>) list.iterator();
		String className = getClassName(t);
		if(StringUtils.isEmpty(className)) {
			return null;
		}
		while (it.hasNext()) {
			T n = (T) it.next();
			Long parentId = ReflectUtils.getFieldValue(n, "parentId");	
			Long classId = ReflectUtils.getFieldValue(t, className.toLowerCase()+"Id");
			if (parentId == classId) {
				tlist.add(n);
			}
		}
		return tlist;
	}

	/**
	 * 判断是否有子节点
	 */
	private boolean hasChild(List<T> list, T t) {
		return getChildList(list, t).size() > 0;
	}
	
	private String getClassName(T t) {
		if(t!=null) {
			String className = t.getClass().getName();
			className = className.substring(className.lastIndexOf(".")+1, className.length());
			//驼峰转下划线
			String underScoreCaseName = StringUtils.toUnderScoreCase(className);
			return underScoreCaseName.split("_")[1];
		}
		return null;
	}
	
	/**
	 * 构建前端所需要树结构
	 * 
	 * @param menus 菜单列表
	 * @return 树结构列表
	 */
	public List<T> buildMenuTree(List<T> list) {
		List<T> returnList = new ArrayList<T>();
		List<Long> tempList = new ArrayList<Long>();
		
		for (T dept : list) {
			tempList.add(ReflectUtils.getFieldValue(dept,getClassName(dept)+"Id"));
		}
		for (Iterator<T> iterator = list.iterator(); iterator.hasNext();) {
			T menu = (T) iterator.next();
			// 如果是顶级节点, 遍历该父节点的所有子节点
			if (!tempList.contains(ReflectUtils.getFieldValue(menu, "parentId"))) {
				recursionFn(list, menu);
				returnList.add(menu);
			}
		}
		if (returnList.isEmpty()) {
			returnList = list;
		}
		return returnList;
	}
	
}
